package org.wesc.boot.webapi.api.system;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.wesc.boot.common.annotation.ApiEndpoint;
import org.wesc.boot.common.api.R;
import org.wesc.boot.dao.entity.Menu;
import org.wesc.boot.dao.model.MenuQueryModel;
import org.wesc.boot.service.system.menu.MenuAdvanceService;
import org.wesc.boot.service.system.router.VueRouter;
import org.wesc.boot.service.system.user.UserAdvanceService;
import org.wesc.boot.webapi.base.BaseApi;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author Wesley
 */
@Api(tags={"菜单接口"})
@Slf4j
@Validated
@RestController
@RequestMapping("/api/menu")
public class MenuApi extends BaseApi {

    private final UserAdvanceService userAdvanceService;

    private final MenuAdvanceService menuAdvanceService;

    @Autowired
    public MenuApi(UserAdvanceService userAdvanceService, MenuAdvanceService menuAdvanceService) {
        this.userAdvanceService = userAdvanceService;
        this.menuAdvanceService = menuAdvanceService;
    }

    @ApiOperation(value = "通过用户名构建 Vue路由")
    @GetMapping("/{username}")
    public R<ArrayList<VueRouter<Menu>>> getUserRouters(@NotBlank(message = "{required}") @PathVariable String username) {
        return R.data(this.userAdvanceService.getUserRouters(username));
    }

    @ApiOperation(value = "查看菜单")
    @GetMapping
    @RequiresPermissions("menu:view")
    public R<Map<String, Object>> menuList(MenuQueryModel menuQueryModel) {
        return R.data(this.menuAdvanceService.findMenus(menuQueryModel));
    }

    @ApiOperation(value = "新建菜单")
    @PostMapping
    @RequiresPermissions("menu:add")
    @ApiEndpoint(operation = "新建菜单", exception = "新建菜单失败")
    public R<String> addMenu(@Valid Menu menu) {
        try {
            this.menuAdvanceService.createMenu(menu);
            return R.success();
        } catch (Exception e) {
            String message = "新增菜单/按钮失败";
            log.error(message, e);
            return R.fail(message);
        }
    }

    @ApiOperation(value = "删除菜单")
    @DeleteMapping("/{menuIds}")
    @RequiresPermissions("menu:delete")
    @ApiEndpoint(operation = "删除菜单", exception = "删除菜单失败")
    public R<String> deleteMenus(@NotBlank(message = "{required}") @PathVariable String menuIds) {
        try {
            String[] strIds = menuIds.split(StringPool.COMMA);
            Long[] ids = new Long[strIds.length];
            for(int i = 0; i < strIds.length; i++) {
                ids[i] = Long.valueOf(strIds[i]);
            }
            this.menuAdvanceService.batchDeleteMenus(ids);
            return R.success();
        } catch (Exception e) {
            String message = "删除菜单/按钮失败";
            log.error(message, e);
            return R.fail(message);
        }
    }

    @ApiOperation(value = "更新菜单")
    @PutMapping
    @RequiresPermissions("menu:update")
    @ApiEndpoint(operation = "更新菜单", exception = "更新菜单失败")
    public R<String> updateMenu(@Valid Menu menu) {
        try {
            this.menuAdvanceService.updateMenu(menu);
            return R.success();
        } catch (Exception e) {
            String message = "修改菜单/按钮失败";
            log.error(message, e);
            return R.fail(message);
        }
    }

    @ApiOperation(value = "导出菜单")
    @PostMapping("/excel/export")
    @RequiresPermissions("menu:export")
    @ApiEndpoint(operation = "导出菜单", exception = "导出菜单失败")
    public void exportExcel(MenuQueryModel menuQueryModel, HttpServletResponse response) throws IOException {
        response.setContentType("APPLICATION/OCTET-STREAM;charset=UTF-8");
        String sheetName = "菜单列表";
        List<Menu> menuList = this.menuAdvanceService.findMenuList(menuQueryModel);
        EasyExcel.write(response.getOutputStream(), Menu.class).sheet(sheetName).doWrite(menuList);
    }
}
